<template>
  <div class="product-container">
    <h2  >产品管理</h2>
    <!-- 查询区域：整合分类多选+搜索+重置 -->
    <div class="search-category-container">
      <el-input
          placeholder="请输入产品名称"
          style="width: 200px"
          v-model="queryProductName"
          class="search-input"
          @keyup.enter="queryByProductName"
      ></el-input>

      <el-button
          @click="queryByProductName"
          type="success"
          plain
          class="search-button"
      >
        查询
      </el-button>
      <el-button
          type="default"
          class="reset-button"
          @click="resetSearch"
      >
        重置
      </el-button>
      <el-button
          @click="showProductDialog"
          type="primary"
          class="register-button"
      >
        新增产品
      </el-button>
    </div>

    <!-- 错误信息 -->
    <div class="error-message">{{ errorMessage }}</div>

    <!-- 产品信息表格 -->
    <el-table
        :data="productList"
        class="product-table"
        header-cell-class-name="table-header"
    >
      <el-table-column
          label="序号"
          type="index"
          width="60px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="productName"
          label="产品名称"
          width="180px"
          align="center"
      ></el-table-column>
      <!-- 价格列带单位 -->
      <el-table-column
          prop="price"
          label="产品价格"
          width="150px"
          align="center"
      >
        <template #default="scope">
          {{ scope.row.price }} 元
        </template>
      </el-table-column>
      <el-table-column
          prop="isAvailable"
          label="是否可用"
          width="120px"
          align="center"
          :formatter="formatAvailability"
      ></el-table-column>
      <el-table-column
          prop="productCategory"
          label="产品类别"
          width="160px"
          align="center"
      ></el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" width="460px" align="center">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button type="primary" size="small" @click="showEditDialog(scope.row.id)">修改</el-button>
            <el-button type="success" size="small" @click="showViewDialog(scope.row.id)">查看</el-button>
            <el-button type="danger"  size="small" @click="confirmRemove(scope.row.id)">下架</el-button>
            <el-button type="warning" size="small" @click="openIngredientDialog(scope.row)">分配小料</el-button>
            <el-button type="info" size="small" @click="openMaterialDialog(scope.row)">分配材料</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          background
          v-model:current-page="pageContains.pageNum"
          v-model:page-size="pageContains.pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageContains.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          class="pagination"
      />
    </div>

    <!-- 产品信息对话框 -->
    <el-dialog
        v-model="productDialog"
        :title="dialogTitle"
        class="product-dialog"
    >
      <el-form :model="curProduct" class="product-form">
        <el-form-item label="产品名称" class="form-item">
          <el-col :span="11">
            <el-input
                v-model="curProduct.productName"
                class="form-input"
                :disabled="dialogOptType === 3"
                placeholder="请输入产品名称"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="产品价格" class="form-item">
          <el-col :span="11">
            <el-input
                v-model="curProduct.price"
                type="number"
                step="0.01"
                class="form-input"
                :disabled="dialogOptType === 3"
                placeholder="请输入产品价格"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="产品描述" class="form-item">
          <el-col :span="11">
            <el-input
                v-model="curProduct.description"
                class="form-input"
                :disabled="dialogOptType === 3"
                placeholder="请输入产品描述"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="产品类别" class="form-item">
          <el-col :span="11">
            <el-select
                v-model="curProduct.productCategory"
                class="form-select"
                :disabled="dialogOptType === 3"
            >
              <el-option
                  v-for="category in productCategories"
                  :key="category"
                  :label="category"
                  :value="category"
              ></el-option>
            </el-select>
          </el-col>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="optOne()" class="dialog-button">{{ buttonOpt }}</el-button>
      </div>
    </el-dialog>

    <!-- 分配小料弹窗 -->
    <el-dialog
        :title="ingredientDialogTitle"
        v-model="ingredientDialogVisible"
        width="1100px"
        top="5vh"
        :close-on-click-modal="false"
    >
      <!-- 当前操作产品信息 -->
      <div class="current-product-info">
        <el-tag type="primary" size="medium">当前操作产品：{{ currentProductName }}</el-tag>
      </div>

      <div class="material-container-horizontal">
        <!-- 左侧：已选小料区域 -->
        <div class="material-panel left-panel">
          <h3>已选小料</h3>
          <div class="panel-content">
            <el-table
                :data="ingredientDialog.assignedList"
                border
                size="small"
                style="width: 100%;"
                row-key="ingredientId"
            >
              <el-table-column prop="ingredientName" label="小料名称" width="170"  align="center"></el-table-column>
              <el-table-column label="额外价格(元)" width="180"  align="center">
                <template #default="scope">
                  <el-input-number
                      v-model="scope.row.extraPrice"
                      :min="0"
                      :step="0.5"
                      :precision="2"
                      style="width: 120px;"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="122" align="center">
                <template #default="scope">
                  <el-button
                      type="text"
                      size="small"
                      style="color: #F56C6C;"
                      @click="removeIngredientImmediate(scope.row)">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div v-if="ingredientDialog.assignedList.length === 0" class="empty-tip">
              <el-empty description="暂无已选小料"></el-empty>
            </div>
          </div>
        </div>

        <!-- 中间分隔线 -->
        <div class="material-divider">
          <el-divider direction="vertical" />
        </div>

        <!-- 右侧：可选小料区域 -->
        <div class="material-panel right-panel">
          <div class="panel-header">
            <h3>可选小料</h3>
            <el-input
                v-model="ingredientSearchKeyword"
                placeholder="搜索小料名称"
                size="small"
                style="width: 180px;"
                @input="handleIngredientSearch"
            >
              <template #append>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>

          <div class="panel-content">
            <el-table
                :data="pagedOptionalIngredients"
                border
                size="small"
                style="width: 100%;"
                row-key="ingredientId"
            >
              <el-table-column width="55" align="center">
                <template #default="scope">
                  <el-checkbox
                      v-model="ingredientCheckedMap[scope.row.ingredientId]"
                      @change="handleIngredientCheck(scope.row, $event)"
                  />
                </template>
              </el-table-column>

              <el-table-column prop="ingredientName" label="小料名称" width="193"  align="center"></el-table-column>
              <el-table-column label="额外价格(元)" width="210"  align="center">
                <template #default="scope">
                  <el-input-number
                      v-model="scope.row.extraPrice"
                      :min="0"
                      :step="0.5"
                      :precision="2"
                      :value="2.00"
                      style="width: 100px;"
                      @change="updateIngredientPrice(scope.row)"
                  ></el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="panel-footer" v-if="filteredOptionalIngredients.length > 0">
            <el-pagination
                background
                v-model:current-page="ingredientPage.currentPage"
                v-model:page-size="ingredientPage.pageSize"
                :page-sizes="[5, 10, 20]"
                layout="total, sizes, prev, pager, next"
                :total="filteredOptionalIngredients.length"
                @size-change="handleIngredientPageSizeChange"
                @current-change="handleIngredientCurrentPageChange"
                size="small"
            />
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="ingredientDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveIngredient">保存分配</el-button>
      </template>
    </el-dialog>

    <!-- 分配基础原料弹窗 -->
    <el-dialog
        :title="materialDialogTitle"
        v-model="materialDialogVisible"
        width="1300px"
        top="5vh"
        :close-on-click-modal="false"
    >
      <!-- 当前操作产品信息 -->
      <div class="current-product-info">
        <el-tag type="primary" size="medium">当前操作产品：{{ currentProductName }}</el-tag>
      </div>

      <div class="material-container-horizontal">
        <!-- 左侧：已选材料区域 -->
        <div class="material-panel left-panel">
          <h3>已选材料</h3>
          <div class="panel-content">
            <el-table
                :data="materialDialog.assignedList"
                border
                size="small"
                style="width: 100%;"
                row-key="ingredientId"
            >
              <el-table-column prop="ingredientName" label="材料名称" width="130" align="center"></el-table-column>

              <el-table-column prop="ingredientType" label="材料类型" width="100" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.ingredientType === '基础原料' ? 'primary' : 'info'">
                    {{ scope.row.ingredientType }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="unit" label="单位" width="82" align="center"></el-table-column>
              <el-table-column label="单份用量" width="160" align="center">
                <template #default="scope">
                  <el-input-number
                      v-model="scope.row.quantityNeeded"
                      :min="0.1"
                      :step="0.1"
                      :precision="2"
                      style="width: 100px;"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center">
                <template #default="scope">
                  <el-button
                      type="text"
                      size="small"
                      style="color: #F56C6C;"
                      @click="removeMaterialImmediate(scope.row)"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div v-if="materialDialog.assignedList.length === 0" class="empty-tip">
              <el-empty description="暂无已选材料"></el-empty>
            </div>
          </div>
        </div>

        <div class="material-divider">
          <el-divider direction="vertical" />
        </div>

        <!-- 右侧：可选材料区域 -->
        <div class="material-panel right-panel">
          <div class="panel-header">
            <h3>可选材料</h3>
            <el-input
                v-model="materialSearchKeyword"
                placeholder="搜索材料名称"
                size="small"
                style="width: 180px;"
                @input="handleMaterialSearch"
            >
              <template #append>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>

          <div class="panel-content">
            <el-table
                :data="pagedOptionalMaterials"
                border
                size="small"
                style="width: 100%;"
                row-key="ingredientId"
            >
              <el-table-column width="55" align="center">
                <template #default="scope">
                  <el-checkbox
                      v-model="materialCheckedMap[scope.row.ingredientId]"
                      @change="handleMaterialCheck(scope.row, $event)"
                  />
                </template>
              </el-table-column>

              <el-table-column prop="ingredientName" label="材料名称" width="130" align="center"></el-table-column>
              <el-table-column prop="ingredientType" label="材料类型" width="100" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.ingredientType === '基础原料' ? 'primary' : 'info'">
                    {{ scope.row.ingredientType }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="unit" label="单位" width="90" align="center"></el-table-column>
              <el-table-column label="单份用量" width="183" align="center">
                <template #default="scope">
                  <el-input-number
                      v-model="scope.row.quantityNeeded"
                      :min="0.1"
                      :step="0.1"
                      :precision="2"
                      :value="1.00"
                      style="width: 100px;"
                      @change="updateMaterialQuantity(scope.row)"
                  ></el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="panel-footer" v-if="filteredOptionalMaterials.length > 0">
            <el-pagination
                background
                v-model:current-page="materialPage.currentPage"
                v-model:page-size="materialPage.pageSize"
                :page-sizes="[5, 10, 20]"
                layout="total, sizes, prev, pager, next"
                :total="filteredOptionalMaterials.length"
                @size-change="handleMaterialPageSizeChange"
                @current-change="handleMaterialCurrentPageChange"
                size="small"
            />
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="materialDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveMaterial">保存分配</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch, computed } from "vue";
import { Search } from '@element-plus/icons-vue';
import http from '@/axios/http';
import { ElMessageBox, ElMessage, ElEmpty, ElLoading } from 'element-plus';

/* 分类相关 */
const categories = ref([]);
const selectedCategories = ref([]);
const queryProductName = ref("");
const errorMessage = ref("");

/* 产品基础数据 */
let productList = ref([]);
let productDialog = ref(false);
let curProduct = ref({
  isAvailable: true,
  productCategory: ""
});
let dialogTitle = ref("");
let buttonOpt = ref("");
let dialogOptType = ref(1); // 1：添加 2：编辑 3：查看

/* 分页相关 */
let pageContains = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

/* 小料分配弹窗相关 */
const ingredientDialogVisible = ref(false);
const ingredientDialogTitle = ref("分配小料");
const ingredientDialog = reactive({
  productId: null,
  assignedList: [],
  optionalList: [],
  selectedOptional: []
});

const ingredientCheckedMap = reactive({});
const ingredientSearchKeyword = ref('');
const ingredientPage = reactive({
  currentPage: 1,
  pageSize: 10
});

// 修复小料搜索时的字段匹配
const filteredOptionalIngredients = computed(() => {
  if (!ingredientSearchKeyword.value) {
    return ingredientDialog.optionalList;
  }
  const keyword = ingredientSearchKeyword.value.trim().toLowerCase();
  return ingredientDialog.optionalList.filter(item =>
      // 确保使用ingredientName字段，兼容可能的undefined情况
      item.ingredientName?.toLowerCase().includes(keyword)
  );
});

const pagedOptionalIngredients = computed(() => {
  const startIndex = (ingredientPage.currentPage - 1) * ingredientPage.pageSize;
  return filteredOptionalIngredients.value.slice(startIndex, startIndex + ingredientPage.pageSize);
});

watch(pagedOptionalIngredients, (newVal) => {
  Object.keys(ingredientCheckedMap).forEach(key => {
    if (!newVal.some(item => item.ingredientId === key)) {
      delete ingredientCheckedMap[key];
    }
  });
  newVal.forEach(item => {
    const isChecked = ingredientDialog.selectedOptional.some(
        selected => selected.ingredientId === item.ingredientId
    );
    ingredientCheckedMap[item.ingredientId] = isChecked;
  });
});

const handleIngredientCheck = (row, checked) => {
  if (checked) {
    const existingIndex = ingredientDialog.selectedOptional.findIndex(
        item => item.ingredientId === row.ingredientId
    );
    if (existingIndex === -1) {
      ingredientDialog.selectedOptional.push(JSON.parse(JSON.stringify(row)));
    }
  } else {
    const index = ingredientDialog.selectedOptional.findIndex(
        item => item.ingredientId === row.ingredientId
    );
    if (index !== -1) {
      ingredientDialog.selectedOptional.splice(index, 1);
    }
  }
};

const updateIngredientPrice = (row) => {
  const index = ingredientDialog.selectedOptional.findIndex(
      item => item.ingredientId === row.ingredientId
  );
  if (index !== -1) {
    ingredientDialog.selectedOptional[index].extraPrice = row.extraPrice;
  }
};

const handleIngredientSearch = () => {
  ingredientPage.currentPage = 1;
};

const handleIngredientPageSizeChange = (size) => {
  ingredientPage.pageSize = size;
  ingredientPage.currentPage = 1;
};

const handleIngredientCurrentPageChange = (page) => {
  ingredientPage.currentPage = page;
};

/* 分类数据获取 */
const fetchCategories = async () => {
  const res = await http.get('/glsb/getAllCategories')
  if (res.data.result === 'success') categories.value = res.data.data || []
}

/* 分类多选逻辑 */
const handleAllCategoryClick = () => {
  selectedCategories.value = [];
};

const resetSearch = () => {
  selectedCategories.value = [];
  queryProductName.value = "";
  pageContains.value.pageNum = 1;
  getAllProducts();
};

/* 基础原料/包装材料分配弹窗相关 */
const materialDialogVisible = ref(false);
const materialDialogTitle = ref("分配基础原料/包装材料");
const materialDialog = reactive({
  productId: null,
  assignedList: [],
  optionalList: [],
  selectedOptional: []
});

// 当前操作的产品名称
const currentProductName = ref('');

const materialCheckedMap = reactive({});
const materialSearchKeyword = ref('');
const materialPage = reactive({
  currentPage: 1,
  pageSize: 10
});

const filteredOptionalMaterials = computed(() => {
  if (!materialSearchKeyword.value) {
    return materialDialog.optionalList;
  }
  const keyword = materialSearchKeyword.value.trim().toLowerCase();
  return materialDialog.optionalList.filter(item =>
      item.ingredientName.toLowerCase().includes(keyword)
  );
});

const pagedOptionalMaterials = computed(() => {
  const startIndex = (materialPage.currentPage - 1) * materialPage.pageSize;
  return filteredOptionalMaterials.value.slice(startIndex, startIndex + materialPage.pageSize);
});

watch(pagedOptionalMaterials, (newVal) => {
  Object.keys(materialCheckedMap).forEach(key => {
    if (!newVal.some(item => item.ingredientId === key)) {
      delete materialCheckedMap[key];
    }
  });
  newVal.forEach(item => {
    const isChecked = materialDialog.selectedOptional.some(
        selected => selected.ingredientId === item.ingredientId
    );
    materialCheckedMap[item.ingredientId] = isChecked;
  });
});

const handleMaterialCheck = (row, checked) => {
  if (checked) {
    const existingIndex = materialDialog.selectedOptional.findIndex(
        item => item.ingredientId === row.ingredientId
    );
    if (existingIndex === -1) {
      materialDialog.selectedOptional.push(JSON.parse(JSON.stringify(row)));
    }
  } else {
    const index = materialDialog.selectedOptional.findIndex(
        item => item.ingredientId === row.ingredientId
    );
    if (index !== -1) {
      materialDialog.selectedOptional.splice(index, 1);
    }
  }
};

const updateMaterialQuantity = (row) => {
  const index = materialDialog.selectedOptional.findIndex(
      item => item.ingredientId === row.ingredientId
  );
  if (index !== -1) {
    materialDialog.selectedOptional[index].quantityNeeded = row.quantityNeeded;
  }
};

const handleMaterialSearch = () => {
  materialPage.currentPage = 1;
};

const handleMaterialPageSizeChange = (size) => {
  materialPage.pageSize = size;
  materialPage.currentPage = 1;
};

const handleMaterialCurrentPageChange = (page) => {
  materialPage.currentPage = page;
};

async function openMaterialDialog(row) {
  const loading = ElLoading.service({
    lock: true,
    text: '加载材料数据中...',
    background: 'rgba(255, 255, 255, 0.7)'
  });

  try {
    currentProductName.value = row.productName;

    materialDialogVisible.value = false;
    materialDialog.productId = row.id;
    materialDialog.assignedList = [];
    materialDialog.optionalList = [];
    materialDialog.selectedOptional = [];
    Object.keys(materialCheckedMap).forEach(key => delete materialCheckedMap[key]);
    materialSearchKeyword.value = '';
    materialPage.currentPage = 1;
    materialPage.pageSize = 10;

    const response = await http.post('/glsb/loadAssignBasePackageMaterials', {
      productId: row.id
    });

    if (response.data.result === 'success') {
      const data = response.data.data;
      materialDialog.assignedList = data.assignedMaterials.map(item => ({
        ingredientId: item.id,
        ingredientName: item.ingredient_name,
        ingredientType: item.ingredient_type,
        unit: item.unit,
        quantityNeeded: Number(item.quantity_needed) || 1.00,
        isDefault: 1
      }));
      materialDialog.optionalList = data.optionalMaterials.map(item => ({
        ingredientId: item.id,
        ingredientName: item.ingredient_name,
        ingredientType: item.ingredient_type,
        unit: item.unit,
        quantityNeeded: 1.00,
        isDefault: 1
      }));
      materialDialogVisible.value = true;
    } else {
      ElMessage.error('加载材料数据失败: ' + response.data.error);
    }
  } catch (e) {
    console.error('打开材料弹窗失败', e);
    ElMessage.error('获取材料失败：' + (e.msg || e.message || '网络错误'));
  } finally {
    loading.close();
  }
}

async function saveMaterial() {
  const loading = ElLoading.service({
    lock: true,
    text: '保存中...',
    background: 'rgba(255, 255, 255, 0.7)'
  });

  try {
    const finalAssignedList = [...materialDialog.assignedList];

    materialDialog.selectedOptional.forEach(selected => {
      const optionalIndex = materialDialog.optionalList.findIndex(
          item => item.ingredientId === selected.ingredientId
      );
      if (optionalIndex !== -1) {
        materialDialog.optionalList.splice(optionalIndex, 1);
      }

      finalAssignedList.push({
        ...selected,
        quantityNeeded: selected.quantityNeeded
      });
    });

    const submitData = {
      productId: materialDialog.productId,
      materials: finalAssignedList.map(item => ({
        ingredientId: item.ingredientId,
        quantityNeeded: item.quantityNeeded,
        isDefault: item.isDefault,
        extraPrice: 0.00
      }))
    };

    const response = await http.post('/glsb/submitAssignBasePackageMaterials', submitData);
    if (response.data.result === 'success') {
      ElMessage.success('材料分配成功');
      materialDialogVisible.value = false;
      materialDialog.selectedOptional = [];
    } else {
      ElMessage.error('材料分配失败: ' + response.data.error);
    }
  } catch (e) {
    console.error('保存材料分配失败', e);
    ElMessage.error('保存失败：' + (e.msg || e.message || '网络错误'));
  } finally {
    loading.close();
  }
}

async function removeMaterialImmediate(row) {
  try {
    await ElMessageBox.confirm(
        `确定要移除材料“${row.ingredientName}”吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    const res = await http.post('/glsb/removeBasePackageMaterial', {
      productId: materialDialog.productId,
      ingredientId: row.ingredientId,
    });

    if (res.data.result === 'success') {
      ElMessage.success('移除成功');
      const idx = materialDialog.assignedList.findIndex(
          i => i.ingredientId === row.ingredientId
      );
      if (idx > -1) {
        const [removed] = materialDialog.assignedList.splice(idx, 1);
        materialDialog.optionalList.push({
          ...removed,
          quantityNeeded: 1.00,
          isDefault: 1,
        });
        materialDialog.optionalList.sort((a, b) =>
            a.ingredientName.localeCompare(b.ingredientName)
        );
      }
    } else {
      ElMessage.error(res.data.error || '移除失败');
    }
  } catch (action) {
    if (action === 'cancel' || action === 'close') {
      ElMessage.info('已取消移除');
    }
  }
}

/* 产品数据接口 */
function getAllProducts() {
  let params = {
    pageNum: pageContains.value.pageNum,
    pageSize: pageContains.value.pageSize,
    productCategories: selectedCategories.value.length ? selectedCategories.value : []
  };

  http.post('/glsb/get_all_products', params).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      pageContains.value = result.data;
      productList.value = result.data.list;
    } else {
      errorMessage.value = result.error;
    }
  });
}

function queryByProductName() {
  let param = {
    productName: queryProductName.value,
    pageNum: pageContains.value.pageNum,
    pageSize: pageContains.value.pageSize,
    productCategories: selectedCategories.value.length ? selectedCategories.value : []
  };
  http.post('/glsb/get_product_by', param).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      pageContains.value = result.data;
      productList.value = result.data.list;
    } else {
      errorMessage.value = result.error;
    }
  });
}

/* 产品对话框操作 */
function showProductDialog() {
  dialogTitle.value = "新增产品";
  buttonOpt.value = "新增";
  productDialog.value = true;
  dialogOptType.value = 1;
  curProduct.value = {
    isAvailable: true,
    productCategory: ""
  };
}

function showViewDialog(productid) {
  getProductInfo(productid);
  productDialog.value = true;
  dialogTitle.value = "查看产品信息";
  buttonOpt.value = "关闭";
  dialogOptType.value = 3;
}

function showEditDialog(productid) {
  getProductInfo(productid);
  productDialog.value = true;
  dialogTitle.value = "产品信息修改";
  buttonOpt.value = "修改";
  dialogOptType.value = 2;
}

function getProductInfo(productid) {
  let param = { id: productid };
  http.post('/glsb/getproductby_id', param).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      curProduct.value = result.data;
      curProduct.value.isAvailable = curProduct.value.isAvailable === 1;
    } else {
      errorMessage.value = result.error;
    }
  });
}

function addOne() {
  let param = curProduct.value;
  if (!param.productName || param.price === undefined) {
    errorMessage.value = "产品名称和产品价格不能为空";
    return;
  }
  param.isAvailable = param.isAvailable ? 1 : 0;
  http.post('/glsb/add_one_product', param).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      ElMessage.success('产品新增成功');
      closeProductDialog();
      getAllProducts();
    } else {
      ElMessage.error(result.error);
    }
  });
}

function editOne() {
  let param = curProduct.value;
  if (!param.id) {
    errorMessage.value = "缺少必要的 id 字段";
    return;
  }
  param.isAvailable = param.isAvailable ? 1 : 0;
  http.post('/glsb/modifyproductby_id', param).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      ElMessage.success('产品修改成功');
      closeProductDialog();
      getAllProducts();
    } else {
      ElMessage.error(result.error);
    }
  });
}

function closeProductDialog() {
  productDialog.value = false;
  curProduct.value = {
    isAvailable: true,
    productCategory: ""
  };
}

function optOne() {
  if (dialogOptType.value === 1) {
    addOne();
  } else if (dialogOptType.value === 2) {
    editOne();
  } else if (dialogOptType.value === 3) {
    closeProductDialog();
  }
}

/* 产品下架操作 */
function removeOne(productid) {
  return ElMessageBox.confirm('确定下架？', '提示', { type: 'warning' })
      .then(() => http.post('/glsb/shelfOff', { id: productid }))
      .then(() => {
        ElMessage.success('下架成功');
        getAllProducts();
      });
}

function confirmRemove(productid) {
  ElMessageBox.confirm(
      '你确定要下架该产品吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    removeOne(productid);
  }).catch(() => {
    ElMessage.info('已取消下架商品操作');
  });
}

/* 小料分配逻辑 */
async function openIngredientDialog(row) {
  const loading = ElLoading.service({
    lock: true,
    text: '加载小料数据中...',
    background: 'rgba(255, 255, 255, 0.7)'
  });

  try {
    currentProductName.value = row.productName;

    ingredientDialogVisible.value = false;
    ingredientDialog.productId = row.id;
    ingredientDialog.assignedList = [];
    ingredientDialog.optionalList = [];
    ingredientDialog.selectedOptional = [];
    Object.keys(ingredientCheckedMap).forEach(key => delete ingredientCheckedMap[key]);
    ingredientSearchKeyword.value = '';
    ingredientPage.currentPage = 1;
    ingredientPage.pageSize = 10;

    const response = await http.post('/glsb/loadAssignIngredientData', {
      productId: row.id
    });

    if (response.data.result === 'success') {
      const data = response.data.data;
      // 修复已选小料名称映射（接口返回ingredient_name，前端需要ingredientName）
      ingredientDialog.assignedList = data.assignedIngredients.map(item => ({
        ingredientId: item.id,
        ingredientName: item.ingredient_name, // 关键修复：将ingredient_name映射为ingredientName
        extraPrice: Number(item.extra_price) || 0,
        isDefault: 0
      }));
      // 可选小料名称映射（接口返回ingredientName，直接使用）
      ingredientDialog.optionalList = data.optionalIngredients.map(item => ({
        ingredientId: item.ingredientId,
        ingredientName: item.ingredientName, // 确保使用正确的字段名
        extraPrice: 2.00,
        isDefault: 0
      }));
      ingredientDialogVisible.value = true;
    } else {
      ElMessage.error('加载小料数据失败: ' + response.data.error);
    }
  } catch (e) {
    console.error('打开小料弹窗失败', e);
    ElMessage.error('获取小料失败：' + (e.msg || e.message || '网络错误'));
  } finally {
    loading.close();
  }
}

// 修复移除小料时的字段保留
async function removeIngredientImmediate(row) {
  try {
    await ElMessageBox.confirm(
        `确定要移除小料“${row.ingredientName}”吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    const res = await http.post('/glsb/removeOneIngredient', {
      productId: ingredientDialog.productId,
      ingredientId: row.ingredientId,
    });

    if (res.data.result === 'success') {
      ElMessage.success('移除成功');
      const idx = ingredientDialog.assignedList.findIndex(
          i => i.ingredientId === row.ingredientId
      );
      if (idx > -1) {
        const [removed] = ingredientDialog.assignedList.splice(idx, 1);
        // 显式保留ingredientName字段，确保移回可选列表后仍能显示
        ingredientDialog.optionalList.push({
          ingredientId: removed.ingredientId,
          ingredientName: removed.ingredientName, // 关键修复：显式保留名称字段
          extraPrice: 2.00,
          isDefault: 0,
        });
        ingredientDialog.optionalList.sort((a, b) =>
            a.ingredientName.localeCompare(b.ingredientName)
        );
      }
    } else {
      ElMessage.error(res.data.error || '移除失败');
    }
  } catch (action) {
    if (action === 'cancel' || action === 'close') {
      ElMessage.info('已取消移除');
    }
  }
}

async function saveIngredient() {
  const loading = ElLoading.service({
    lock: true,
    text: '保存中...',
    background: 'rgba(255, 255, 255, 0.7)'
  });

  try {
    const finalAssignedList = [...ingredientDialog.assignedList];

    ingredientDialog.selectedOptional.forEach(selected => {
      const optionalIndex = ingredientDialog.optionalList.findIndex(
          item => item.ingredientId === selected.ingredientId
      );
      if (optionalIndex !== -1) {
        ingredientDialog.optionalList.splice(optionalIndex, 1);
      }

      finalAssignedList.push({
        ...selected,
        extraPrice: selected.extraPrice
      });
    });

    const submitData = {
      productId: ingredientDialog.productId,
      newIngredients: finalAssignedList.map(item => ({
        ingredientId: item.ingredientId,
        extraPrice: item.extraPrice,
        isDefault: item.isDefault
      }))
    };

    const response = await http.post('/glsb/submitAssignIngredients', submitData);
    if (response.data.result === 'success') {
      ElMessage.success('小料分配成功');
      ingredientDialogVisible.value = false;
      ingredientDialog.selectedOptional = [];
    } else {
      ElMessage.error('小料分配失败: ' + response.data.error);
    }
  } catch (e) {
    console.error('保存小料分配失败', e);
    ElMessage.error('保存失败：' + (e.msg || e.message || '网络错误'));
  } finally {
    loading.close();
  }
}

/* 分页处理 */
const handlePageChange = (pageNum1) => {
  pageContains.value.pageNum = pageNum1;
  queryProductName.value ? queryByProductName() : getAllProducts();
};

const handleSizeChange = (pageSize1) => {
  pageContains.value.pageSize = pageSize1;
  queryProductName.value ? queryByProductName() : getAllProducts();
};

/* 初始化 */
let productCategories = ref([]);
function getProductCategories() {
  http.get('/glsb/getAllCategories').then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      productCategories.value = result.data;
    } else {
      errorMessage.value = result.error;
    }
  });
}

watch(selectedCategories, (newVal) => {
  if (newVal !== undefined) {
    pageContains.value.pageNum = 1;
    getAllProducts();
  }
}, { immediate: false });

onMounted(() => {
  init();
  fetchCategories();
});

function init() {
  getAllProducts();
  getProductCategories();
}

function formatAvailability(row, column) {
  return row[column.property] === 1 ? '是' : '否';
}
</script>

<style scoped>
.product-container {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.product-container:hover {
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.15);
}

.search-category-container {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.category-select {
  width: 220px;
}

.search-input {
  border: 1px solid #e0e0e0;
  transition: border-color 0.3s ease;
}

.search-input:hover,
.search-input:focus {
  border-color: #2196F3;
}

.search-button,
.reset-button,
.register-button {
  transition: transform 0.2s ease;
}

.search-button:hover,
.reset-button:hover,
.register-button:hover {
  transform: translateY(-1px);
}

.product-table {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}

.table-header {
  background-color: #f5f5f5;
  color: #333;
}

.el-table__row {
  transition: background-color 0.3s ease;
}

.el-table__row:hover {
  background-color: #f8f9fa;
}

.operation-buttons {
  display: flex;
  gap: 5px;
  justify-content: center;
  flex-wrap: nowrap;
}

.operation-buttons .el-button--small {
  padding: 4px 8px;
  font-size: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.product-dialog {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
}

.form-item {
  margin-bottom: 15px;
}

.form-input, .form-select {
  width: 100%;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}

.dialog-button {
  width: 100%;
  padding: 10px;
}

/* 当前产品信息显示样式 */
.current-product-info {
  margin: 0 0 15px 0;
  padding: 8px 12px;
  background-color: #f0f7ff;
  border-radius: 4px;
}

.material-container-horizontal {
  display: flex;
  height: 450px;
  gap: 15px;
  padding: 10px 0;
}

.material-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fafbfc;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.material-panel h3 {
  margin: 0;
  padding: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
  background-color: #f1f5f9;
  border-bottom: 1px solid #e2e8f0;
}

.panel-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #f1f5f9;
  border-bottom: 1px solid #e2e8f0;
}

.panel-footer {
  padding: 12px 16px;
  border-top: 1px solid #e2e8f0;
  background-color: #fff;
}

.material-divider {
  display: flex;
  align-items: center;
  padding: 0 5px;
}

.left-panel .el-table,
.right-panel .el-table {
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #e2e8f0;
}

.left-panel .el-table__header-wrapper,
.right-panel .el-table__header-wrapper {
  background-color: #2d3748;
}

.left-panel .el-table th,
.right-panel .el-table th {
  color: #fff;
  font-weight: 500;
  border-bottom: none;
}

.left-panel .el-table__row:hover,
.right-panel .el-table__row:hover {
  background-color: #f7fafc;
}

.el-input-number {
  width: 140px !important;
}

.el-input-number__decrease,
.el-input-number__increase {
  width: 36px !important;
}

.el-input-number__input {
  width: 68px !important;
  text-align: center;
}

.empty-tip {
  text-align: center;
  padding: 40px 0;
  background-color: #fff;
  border-radius: 6px;
  margin-top: 8px;
}

.error-messagce {
  color: #F56C6C;
  margin-bottom: 16px;
  height: 20px;
  line-height: 20px;
}

.reset-button {
  background: #fff;
  color: #666;
  border: 1px solid #dcdfe6;
  width: 80px;
}

@media (max-width: 768px) {
  .search-category-container {
    flex-direction: column;
    align-items: flex-start;
  }
  .category-select, .search-input {
    width: 100%;
  }

  .operation-buttons {
    flex-wrap: wrap;
  }
}
</style>